/**
 * yiqihao(一起好商务股份有限公司) copyright 
 */
package com.p2p.base.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.p2p.base.result.ImgUploadResult;

/**
 *
 * @author leiruiqi@yiqihao.com
 *
 *         2015年3月13日 下午4:39:21
 */
public class ImgUploadUtil {

	public static ImgUploadResult saveUploadFile(HttpServletRequest request, String imagePath) {
		
		ImgUploadResult result = new ImgUploadResult();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		//String finalFileName = "";
		List<String> finalFileNameList = new ArrayList<String>();
		
		Map<String,String> uploadNameList = new HashMap<String,String>();
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 取得当前上传文件的文件名称
					String fileName = file.getOriginalFilename();
					String finalName = "";
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if (StringUtils.isNotEmpty(fileName)) {
						String[] strs = fileName.split("\\.");
						String fileExtention = "png";
						// 重命名上传后的文件名
						if (strs.length >= 2) {
							fileExtention = strs[strs.length - 1];
						}
						try {
							String randomName = DateFormatUtil.format(
									new Date(), "yyyyMMddHHmmssSSS");
							finalName = MD5Util.sha1(randomName) + "."
									+ fileExtention;
							//finalFileName += fileName + ",";
							
							String path = imagePath + File.separator + finalName;
							File localFile = new File(path);
							file.transferTo(localFile);
							uploadNameList.put(finalName, fileName);
							//finalFileNameList.add(finalName);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}

			}

		}
		if(uploadNameList.size()>0){
			result.setSuccess(true);
			result.setSuccessFinalFileNameInfoList(uploadNameList);
		}
		
		return result;
		
	}
	
	public static void deleteImageFile(String path){
		File targetFile = new File(path);
		if (targetFile.exists()) {// 图片不存在则直接删除数据库记录
			Boolean result = targetFile.delete();
		} 
	}
}
